package me.xue.communityhealth.admin.controller;

import me.xue.communityhealth.model.DrugSupplier;
import me.xue.communityhealth.service.DrugSupplierService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
public class DrugSupplierController {

    private final DrugSupplierService service;

    @Autowired
    public DrugSupplierController(DrugSupplierService service) {
        this.service = service;
    }

    @GetMapping("/drugSuppliers")
    public String all(Model model) {
        List<DrugSupplier> drugSuppliers = service.findAll();
        model.addAttribute("drugSuppliers", drugSuppliers);
        return "drug_suppliers";
    }

    @GetMapping("/drugSupplier/add")
    public String addPage(Model model) {
        model.addAttribute("drugSupplier", new DrugSupplier());
        return "drug_supplier_edit";
    }

    @PostMapping("/drugSupplier")
    public String add(DrugSupplier drugSupplier) {
        if (service.save(drugSupplier) == 1) {
            return "redirect:/drugSuppliers";
        }
        return "drug_supplier_edit";
    }

    @DeleteMapping("/drugSupplier/{id:\\d+}")
    @ResponseBody
    public String delete(@PathVariable("id") Integer id) {
        if (service.delete(id) == 1) {
            return "success";
        }
        return "fail";
    }

    @GetMapping("/drugSupplier/{id:\\d+}/edit")
    public String updatePage(@PathVariable("id") Integer id, Model model) {
        DrugSupplier drugSupplier = service.findOne(id);
        model.addAttribute("drugSupplier", drugSupplier);
        return "drug_supplier_edit";
    }

    @PutMapping("/drugSupplier")
    public String update(DrugSupplier drugSupplier) {
        if (service.update(drugSupplier) == 1) {
            return "redirect:/drugSuppliers";
        }
        return "drug_supplier_edit";
    }

}
